/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.common.websocket;

import org.apache.log4j.Logger;

/**
 * description:  客户端实现
 *
 * @author dyhou 创建时间：2017-6-20
 */
public class WebsocketClient {

    private static WebsocketClient instance;

    private Logger log = Logger.getLogger("web socket");

    private WebsocketClient() {
    }

    public static synchronized WebsocketClient getInstance() {
        if (null == instance) {
            instance = new WebsocketClient();
        }
        return instance;
    }

    public void sendMessage(final String configKey, final String url, final String requestParams,
            final String message) {
        new Thread(new Runnable() {

            public void run() {
                WebsocketEndpoint clientEndPoint = null;
                try {
                    clientEndPoint = WebsocketEndpoint
                            .getWebsocketClient(configKey, url, requestParams);
                    // send message to websocket
                    clientEndPoint.send(message);
                    // wait 5 seconds for messages from websocket
                    Thread.sleep(3000);
                } catch (Exception ex) {
                    log.error("web socket exception: " + ex.getMessage());
                } finally {
                    if (null != clientEndPoint) {
                        clientEndPoint.close();
                    }
                    clientEndPoint = null;
                }
            }
        }).start();
    }
}
